package com.servlet3.test;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/12/11 19:12
 */
@WebServlet(urlPatterns = "/asynchello", asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {
    private static final long serialVersionUID = 2709956976464792822L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.支持异步处理asyncSupported = true
        //2.开始异步模式
        System.out.println("主线程" + Thread.currentThread() + " start...");

        AsyncContext asyncContext = req.startAsync();

        //3.业务逻辑进行异步处理，开始异步处理
        asyncContext.start(() -> {
            System.out.println(Thread.currentThread() + " start...");
            hello();
            asyncContext.complete();
            //获取到异步的上下文
//            AsyncContext context = req.getAsyncContext();
            //4.获取响应
            ServletResponse response = asyncContext.getResponse();
            try {
                response.getWriter().println("hello async mode...");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread() + " finish...");
        });
        System.out.println("主线程" + Thread.currentThread() + " finish...");
    }

    public void hello() {
        System.out.println(Thread.currentThread() + " processing...");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
